﻿using Autofac;
using Autofac.Integration.Mvc;
using Autofac.Integration.WebApi;
using ML.Utils;
using System;
using System.Reflection;
using System.Web.Http;
using System.Web.Mvc;

namespace ML.Plug
{
    /// <summary>
    /// AutoFac注册中心配置文件
    /// </summary>
    public class AutoFacConfig
    {
        /// <summary>
        /// AutoFac Web注册中心
        /// </summary>
        public static void RegisterWeb()
        {
            ContainerBuilder builder = new ContainerBuilder();

            //告诉AutoFac控制器工厂，控制器类的创建去哪些程序集中查找
            Assembly controllerAss = Assembly.Load("ML.Web.Controllers");
            builder.RegisterControllers(controllerAss);

            //告诉AutoFac容器，创建项目中的指定类的对象实例，以接口的形式存储
            Assembly repository = Assembly.Load("ML.Repository");
            Type[] repositoryTypes = repository.GetTypes();
            builder.RegisterTypes(repositoryTypes).AsImplementedInterfaces();

            Assembly business = Assembly.Load("ML.Business");
            Type[] businessTypes = business.GetTypes();
            builder.RegisterTypes(businessTypes).AsImplementedInterfaces();

            //其它对外开始的注入
            builder.RegisterType<NLogLogger>().As<ILogger>();

            var container = builder.Build();
            DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
        }

        /// <summary>
        /// AutoFac Web注册中心
        /// </summary>
        public static void RegisterWebApi()
        {
            var builder = new ContainerBuilder();

            //告诉AutoFac控制器工厂，控制器类的创建去哪些程序集中查找
            Assembly controllerAss = Assembly.Load("ML.WebApi.Controllers");
            builder.RegisterApiControllers(controllerAss);
            builder.RegisterControllers(controllerAss);

            //告诉AutoFac容器，创建项目中的指定类的对象实例，以接口的形式存储
            Assembly repository = Assembly.Load("ML.Repository");
            Type[] repositoryTypes = repository.GetTypes();
            builder.RegisterTypes(repositoryTypes).AsImplementedInterfaces();

            Assembly business = Assembly.Load("ML.Business");
            Type[] businessTypes = business.GetTypes();
            builder.RegisterTypes(businessTypes).AsImplementedInterfaces();

            //其它对外开始的注入
            //builder.RegisterType<UserBusiness>().As<IUserBusiness>().InstancePerRequest();

            var config = GlobalConfiguration.Configuration;
            builder.RegisterWebApiFilterProvider(config);

            var container = builder.Build();
            DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
            config.DependencyResolver = new AutofacWebApiDependencyResolver(container);
        }
    }
}